<template>
	<coreshop-page title="我的订单" mode="left">
		<view class="layout-order-box">
			<view class="tab-box">
				<uv-tabs :list="state.tabList" :activeStyle="{ 'color': '#D33123' }" lineColor="#D33123" :lineWidth="40"
					:scrollable="false" :current="state.tabsCurrent" keyName="title" @click="handleChangeTab"></uv-tabs>
			</view>

			<view class="order-list-box">
				<view class="order-box">
					<view v-if="state.orderList.length > 0">
						<view class="item-box" v-for="item, index in state.orderList" :key="index">
							<view class="order-id-box">
								<view class="order-id">
									<uv-icon name="order" color="#606266" size="17"></uv-icon>
									<text class="tit">订单号：{{ item.orderId }}</text>
								</view>
								<view class="order-status">
									<view v-if="item.status === OrderStatusEnum.pending">
										<uv-tags :text="handleStatusText(item)" type="primary" size="mini"
											plain></uv-tags>
									</view>
									<view v-if="item.status === OrderStatusEnum.complete">
										<uv-tags text="已完成" type="success" size="mini"></uv-tags>
									</view>
									<view v-if="item.status === OrderStatusEnum.cancel">
										<uv-tags text="已取消" type="info" size="mini"></uv-tags>
									</view>
								</view>
							</view>
							<view class="goods-box">
								<view class="item-goods" v-for="itemChild in item.items" :key="itemChild.id">
									<coreshop-goods-card type="horizontal" imgHeight="140rpx" imgWidth="140rpx"
										:goodsData="hanldeCombinationGoodsData(itemChild)">
										<template #goodPrice>
											<view class="goods-price">
												<view class="price-box">
													<view class="price">￥{{ itemChild.price }}</view>
													<view class="num">x{{ itemChild.nums }}</view>
												</view>
											</view>
										</template>
									</coreshop-goods-card>
								</view>
							</view>
							<view class="total-box">
								<view class="time"> 下单时间：{{ item.createTime }}</view>
								<view class="total">
									共{{ item.items.length }}件商品 合计:
									<text class="price"> ￥{{ item.orderAmount }} </text>
								</view>
							</view>
							<view class="time-box">
								<uv-tags size="mini" :text="item.typeText" type="success"></uv-tags>
								<view class="btn-box">
									<view class="btn"
										@click="handleRouteNavigateTo(`/pages/subpackage/member/order/detail/detail?orderId=${item.orderId}`)">
										查看详情
									</view>
									<view class="btn pay"
										@click="handleRouteNavigateTo(`/pages/order/pay/pay?orderId=${item.orderId}&orderType=${item.orderType}`)"
										v-if="item.status === OrderStatusEnum.pending && item.payStatus === OrderPayStatusEnum.no">
										立即支付</view>
									<view class="btn receipt" @click="handleConfirmReceiptGoods(item)"
										v-if="item.status === OrderStatusEnum.pending && item.payStatus >= OrderPayStatusEnum.yes && item.shipStatus >= OrderShipStatusEnum.yes && item.confirmStatus === OrderConfirmStatusEnum.receiptNotConfirmed">
										确认收货</view>
									<view class="btn evaluate"
										@click="handleRouteNavigateTo(`/pages/subpackage/member/order/evaluate/evaluate?orderId=${item.orderId}`)"
										v-if="item.status === OrderStatusEnum.pending && item.payStatus >= OrderPayStatusEnum.yes && item.shipStatus >= OrderShipStatusEnum.yes && item.confirmStatus >= OrderConfirmStatusEnum.confirmReceipt && !item.isComment">
										立即评价</view>
								</view>
							</view>
						</view>
						<view class="no-data" v-if="state.page === state.totalPages">没有更多了</view>
					</view>
					<view v-else>
						<coreshop-empty :mode="EmptyEnum.order" text="暂无订单"></coreshop-empty>
					</view>
				</view>
			</view>
		</view>
	</coreshop-page>
</template>
<script setup lang="ts">
	import { reactive } from 'vue';
	import { OrderTabStatusEnum, PayMethodCodeEnum, EmptyEnum, OrderStatusEnum, OrderPayStatusEnum, OrderShipStatusEnum, OrderConfirmStatusEnum } from '@/core/enum';
	import { onLoad, onShow } from '@dcloudio/uni-app';
	import { queryOrderList, queryOrderPayInfo, queryOrderShippingList, queryOrderConfirm } from '@/core/api';
	import type { Response } from '@/core/models';
	import { onReachBottom } from '@dcloudio/uni-app';
	import { handleRouteNavigateTo, handleShowToast } from '@/core/utils';

	interface QueryParams {
		type : OrderTabStatusEnum
	}

	const state = reactive<{
		tabList : Array<{
			title : string;
			id : OrderTabStatusEnum;
		}>;
		page : number;
		limit : number;
		totalPages : number;
		status : OrderTabStatusEnum;
		orderList : Array<any>;
		tabsCurrent : number;
	}>({
		tabList: [
			{
				title: "全部",
				id: OrderTabStatusEnum.all,
			}, {
				title: "待付款",
				id: OrderTabStatusEnum.pendingPayment,
			}, {
				title: "待发货",
				id: OrderTabStatusEnum.pendingShipment,
			}, {
				title: "待收货",
				id: OrderTabStatusEnum.pendingReceipt,
			}, {
				title: "待评价",
				id: OrderTabStatusEnum.pendingEvaluated,
			}
		],
		page: 1,
		limit: 10,
		totalPages: 1,
		status: OrderTabStatusEnum.all,
		orderList: [],
		tabsCurrent: 0,
	});

	onLoad((query : QueryParams) => {
		if (query?.type) {
			state.status = query?.type;
			state.tabsCurrent = state.tabList.findIndex((item : any) => item.id == query?.type);
		}
	})

	onShow(() => {
		state.orderList = [];
		getOrderList();
	})

	/** 下拉加载 */
	onReachBottom(() => {
		if (state.totalPages > state.page) {
			state.page++;
			getOrderList();
		}
	})

	/** 获取订单列表 */
	const getOrderList = async () => {
		uni.showLoading({ title: '加载中...' });
		const orderList : Response<any> = await queryOrderList({
			page: state.page,
			limit: state.limit,
			status: state.status
		});
		state.totalPages = Math.ceil(orderList.data?.count / state.limit);
		state.orderList = state.orderList.concat(orderList.data?.list);
		uni.hideLoading();
	}

	/** 切换tab */
	const handleChangeTab = (e : any) => {
		if (e.id != state.status) {
			state.status = e.id;
			state.page = 1;
			state.orderList = [];
			getOrderList();
		}
	}

	/** 组合商品数据传入组件 */
	const hanldeCombinationGoodsData = (item : any) => {
		return {
			id: item.id,
			image: item.imageUrl,
			name: item.name,
			brief: item.addon,
		}
	}

	/** 确认收货提示 */
	const handleConfirmReceiptGoods = (item : any) => {
		uni.showModal({
			title: "温馨提示",
			content: "您确认收货吗?",
			async success(res : any) {
				if (res.confirm) {
					// #ifdef MP-WEIXIN
					const orderPayInfo = await queryOrderPayInfo({ id: item.orderId });

					if (orderPayInfo.status && orderPayInfo.data.paymentCode == PayMethodCodeEnum.wechatpay && orderPayInfo.data.status == OrderPayStatusEnum.yes) {
						getOrderShippingList(item.orderId, orderPayInfo.data.tradeNo);
					} else if (orderPayInfo.status && orderPayInfo.data.paymentCode != PayMethodCodeEnum.wechatpay && orderPayInfo.data.status == OrderPayStatusEnum.yes) {
						handleConfirmOrder(item.orderId);
					} else {
						handleShowToast(orderPayInfo.msg);
					}
					// #endif

					// #ifndef MP-WEIXIN
					handleConfirmOrder(item.orderId);
					// #endif
				}
			}
		})
	}

	/** 查询当前订单是否接入微信发货信息管理 */
	const getOrderShippingList = async (orderId : string, id : string | number) => {
		const orderShippingList = await queryOrderShippingList({ id, });
		if (orderShippingList.status && orderShippingList.data) {
			if (wx.openBusinessView) {
				wx.openBusinessView({
					businessType: 'weappOrderConfirm',
					extraData: {
						transaction_id: id,
					},
					success() {
						handleConfirmOrder(orderId);
					}
				});
			} else {
				handleShowToast('您的微信版本过低，请升级微信');
			}
		} else {
			handleConfirmOrder(orderId);
		}
	}

	/** 确认收货，确认订单 */
	const handleConfirmOrder = async (id : string) => {
		const orderConfirm = await queryOrderConfirm({ id, });
		if (orderConfirm?.status) {
			handleShowToast('确认收货成功', 'success', () => {
				setTimeout(() => {
					state.page = 1;
					state.orderList = [];
					getOrderList();
				}, 2000)
			});
		} else {
			handleShowToast(orderConfirm?.msg);
		}
	}

	/**订单状态 */
	const handleStatusText = (item : any) => {
		let text : string = "";
		if (item.payStatus === OrderPayStatusEnum.no) {
			text = '待付款';
		} else if (item.payStatus >= OrderPayStatusEnum.yes && item.shipStatus === OrderShipStatusEnum.no) {
			text = '待发货';
		} else if (item.payStatus >= OrderPayStatusEnum.yes && item.shipStatus === OrderShipStatusEnum.partialNo) {
			text = '部分发货';
		} else if (item.payStatus >= OrderPayStatusEnum.yes && item.shipStatus >= OrderShipStatusEnum.yes && item.confirmStatus === OrderConfirmStatusEnum.receiptNotConfirmed) {
			text = '已发货';
		} else if (item.payStatus >= OrderPayStatusEnum.yes && item.shipStatus >= OrderShipStatusEnum.yes && item.confirmStatus >= OrderConfirmStatusEnum.confirmReceipt && item.isComment === false) {
			text = '待评价';
		} else if (item.payStatus >= OrderPayStatusEnum.yes && item.shipStatus >= OrderShipStatusEnum.yes && item.confirmStatus >= OrderConfirmStatusEnum.confirmReceipt && item.isComment === true) {
			text = '已评价';
		}
		return text;
	}
</script>
<style lang="scss" scoped>
	@import './list.scss';
</style>